package com.myreminder.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.myreminder.client.widgets.CreateReminder;
import com.myreminder.client.widgets.ReminderTable;
import com.myreminder.data.User;
import com.myreminder.service.FacebookUserService;
import com.myreminder.service.FacebookUserServiceAsync;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class MyReminder implements EntryPoint {
	
	private static final FacebookUserServiceAsync facebookUserService = GWT.create(FacebookUserService.class);
	public static User currentUser;
	public static ReminderTable table;
	
	public static Button loginButton = new Button();

	public void onModuleLoad() {
		loginButton.setStyleName("facebookLoginButton");
		
		loginButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				loginButton.setStyleName("facebookLoginButtonLoading");
				MyReminder.loginToFacebook();
			}
		});
		RootPanel.get("contentHeader").add(loginButton);
	}
	
	public static native void loginToFacebook() /*-{
		$wnd.FB.init({appId: '197074313646314', status: true, cookie: true,xfbml: true});
		$wnd.FB.login(function(response) {
			if (response.session) {
				$wnd.FB.api('/me', function(response) {
					console.log(response);
					@com.myreminder.client.MyReminder::user(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)(response.id,response.name,response.email);
				});
			} else {
				// user cancelled login
				alert("no!");
			}
		}, {perms:'email'});
	}-*/;
	
	public static void user(String userID,String name,String email){
		facebookUserService.loginOrRegister(userID, name, email, new AsyncCallback<User>() {
			@Override
			public void onFailure(Throwable caught) {
				RootPanel.get().add(new Label("Fail!"));
			}

			@Override
			public void onSuccess(User result) {
				RootPanel.get("contentHeader").remove(loginButton);
				currentUser = result;	
				RootPanel.get("contentHeader").add(new Label(currentUser.name));
				
				table = new ReminderTable(currentUser);
				CreateReminder newReminder = new CreateReminder(currentUser);
				RootPanel.get("contentMain").add(newReminder);
				RootPanel.get("contentMain").add(table);

			}
		});
	}
}